﻿using FySystem.Net.FyNetConnection;
using FySystem.Net.FyNetConnection.Src;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;

namespace FySystem.Net.IOT.RemoteControl
{
    public class RemoteControlListenerA
    {
        public int Port { get; private set; }

        public Func<StateObjectBase, RemoteCommand, RemoteResult> ReceiveCallback { get; private set; }

        public RemoteControlListenerA(int port, Func<StateObjectBase, RemoteCommand, RemoteResult> receiveCallback)
        {
            Port = port;
            ReceiveCallback = receiveCallback;
        }

        public void Start()
        {
            try
            {
                FyServer server = new FyServer();
                server.SetIpAddress(IPAddress.Any)
                        .SetPort(Port)
                        .SetReceiveBufferSize(4096)                             //远控消息可能会比较长，所以设大一点
                        .SetSubPackageMode(SubPackageMode.None)
                        .SetExceptionCallback((ex, socket) =>
                        {
                            try
                            {
                                if (socket != null)
                                    socket.Dispose();
                            }
                            catch (Exception e)
                            {
                                FyLogContext.Write(e.Message);
                            }
                        })
                        .SetReceiveCallback((server, stateObject, data) =>
                        {
                            try
                            {
                                string jsn = Encoding.UTF8.GetString(data, 0, data.Length);
                                RemoteCommand command = JsonSerializer.Deserialize<RemoteCommand>(jsn, new JsonSerializerOptions()
                                {
                                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                                });

                                RemoteResult remoteResult = ReceiveCallback?.Invoke(stateObject, command);

                                //将远控结果返回给客户端
                                SendResult(stateObject, remoteResult);
                            }
                            catch { }
                        });

                server.Execute(null, null);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void SendResult(StateObjectBase stateObject, RemoteResult remoteResult)
        {
            try
            {
                remoteResult = remoteResult == null ? new RemoteResult() : remoteResult;
                string jsn = JsonSerializer.Serialize(remoteResult, new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
                byte[] buffer = Encoding.UTF8.GetBytes(jsn);

                stateObject.WorkSocket.Send(buffer);
            }
            catch (Exception ex)
            {
                FyLogContext.Write(ex.Message);
            }
        }
    }
}
